﻿using System;
using System.Data;
using System.Windows.Forms;

namespace CSW.Framework.UI
{
    /// <summary>
    /// Clipboard Utils.
    /// </summary>
    public static class ClipboardUtils
    {
        /// <summary>
        /// Gets a <see cref="DataTable"/> from the clipboard.
        /// </summary>
        public static DataTable GetDataTable()
        {
            return GetDataTable(true);
        }

        /// <summary>
        /// Gets a <see cref="DataTable"/> from the clipboard.
        /// </summary>
        /// <param name="verbose">if set to <c>true</c> the method will inform the user if there is no data in the clipboard. (default = <c>true</c>)</param>
        public static DataTable GetDataTable(bool verbose)
        {
            IDataObject iData = Clipboard.GetDataObject();

            // Determine whether the data is in a format you can use.
            if (iData == null || !iData.GetDataPresent(DataFormats.Text))
            {
                if (verbose)
                    MessageBox.Show("No data in clipboard.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return null;
            }

            string sheet = (string) iData.GetData(DataFormats.Text);
            DataTable dt = new DataTable();

            foreach (string line in sheet.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {
                if (line == null || line.Trim() == string.Empty)
                    continue;

                string[] values = line.Split("\t".ToCharArray());

                // Trim values
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = values[i].Trim();
                }

                // Add columns
                if (dt.Rows.Count == 0)
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        dt.Columns.Add();
                    }
                }

                // Add row
                dt.Rows.Add(values);
            }

            return dt;
        }
    }
}
